package com.bookstore.Controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bookstore.Domain.*;

import com.bookstore.Service.BookService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.json.JSONObject;
import org.json.JSONStringer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.spring.web.json.Json;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.bookstore.Domain.Code.MSG_OK;

/**
 * @author 未来
 */
@CrossOrigin
@Controller
@RequestMapping("/books")
public class BookController {


    private final BookService bookService;

    @Autowired
    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    @ApiOperation("获取所有书籍信息")
    @GetMapping
    @ResponseBody
    public Result getAll() {
        List<Book> books = bookService.findAll();
        Integer code = books != null ? Code.GET_OK : Code.GET_ERR;
        String msg = books != null ? MSG_OK : Code.MSG_ERR;
        return new Result(code, books, msg);
    }

    @GetMapping("/{book_name}")
    @ResponseBody
    public Result getByName(@ApiParam("String[书籍名]") @PathVariable String book_name) {
        Book book = bookService.findByName(book_name);
        Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
        String msg = book != null ? MSG_OK : Code.MSG_ERR;
        return new Result(code, book, msg);
    }

    @PutMapping
    @ResponseBody
    public Result updateBook(@RequestBody Book book) {
        boolean flag = bookService.updateBook(book);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag ? MSG_OK : Code.MSG_ERR);
    }

    @PostMapping
    @ResponseBody
    public Result save(@RequestBody Book book) {

        boolean flag = bookService.saveBook(book);
        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);
    }

    /**
     * 图书借阅
     * @param book
     * @return
     */
    @PostMapping("/borrows")
    @ResponseBody
    public Result borrows(@RequestBody Book book) {
        boolean flag = bookService.borrows(book);
        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);
    }

    /**
     * 图借阅详情
     * @return
     */
    @GetMapping("/borrow")
    @ResponseBody
    public Result borrow() {
        List<Borrows> books = bookService.getAllborrow();
        Integer code = books != null ? Code.GET_OK : Code.GET_ERR;
        String msg = books != null ? MSG_OK : Code.MSG_ERR;
        return new Result(code, books, msg);
    }

    @GetMapping("/{page}/{number}")
    @ResponseBody
    public Result getPages(@ApiParam("Integer[页数]") @PathVariable Integer page, @ApiParam("Integer[每页数量]") @PathVariable Integer number) {
        System.out.println("访问页数" + page + "=====>" + "访问每页数量" + number);
        List<Book> books = bookService.getPages(page, number);
        Integer code = books != null ? Code.GET_OK : Code.GET_ERR;
        String msg = books != null ? MSG_OK : Code.MSG_ERR;
        return new Result(code, books, msg);
    }

    @GetMapping("/getBook_time/{start_time}/{end_time}")
    @ResponseBody
    public Result getBook_time(@PathVariable String start_time, @PathVariable String end_time) {
        List<Book> books = bookService.getBook_time(start_time, end_time);
        Integer code = books != null ? Code.GET_OK : Code.GET_ERR;
        String msg = books != null ? MSG_OK : Code.MSG_ERR;
        return new Result(code, books, msg);
    }

    @DeleteMapping("/{id}")
    @ResponseBody
    public Result deleteBook(@PathVariable Integer id) {
        boolean flag = bookService.deleteBook(id);
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR, flag);
    }

    @DeleteMapping
    @ResponseBody
    public Result deleteBook(@RequestBody int[] ids) {
        boolean flag = bookService.deleteBookAlist(ids);
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR, flag);
    }

    @PostMapping("/save")
    @ResponseBody
    public Result postBookImages(@RequestParam("file") MultipartFile file, @RequestParam("id") Integer id, @RequestParam("book") String book) {
        //@RequestParam("book") Book book:不能解析，
        //@RequestBody:这个是解析前端json数据的但是不能用！
        //@RequestParam("book") String book：只能用这个注解获取值，不能用
        Book book1 = JSON.parseObject(book, Book.class);
        String resources = "";
        boolean flag = false;
        try {
            // 保存图片文件到本地
            String fileName = file.getOriginalFilename();
            //设置书籍图片地址
            System.out.println("file:" + fileName);
            //获取当前在本机的工作目录路径
            String property = System.getProperty("user.dir");
            // 获取最后一个"."的位置
            int lastIndexOfDot = fileName.lastIndexOf(".");
            // 获取文件后缀名
            String suffix = fileName.substring(lastIndexOfDot + 1);
            if ("png".equals(suffix) || "gif".equals(suffix) || "jpg".equals(suffix) || "jpeg".equals(suffix)) {
                resources = "\\src\\main\\resources\\static\\images\\";
            } else if ("txt".equals(suffix)) {
                resources = "\\src\\main\\resources\\static\\text\\";
            }
            //资源放置的位置
            //存放txt资源目录
            String destPath = property + resources + fileName;
            File dest = new File(destPath);
            if (dest.exists()) {
                return new Result(Code.SAVE_ERR, "图片已存在！");
            } else {
                //图片不存在加入
                //如果文件有会自动覆盖
                file.transferTo(dest);
                // 这里你可能也需要将文件ID或其他信息保存到数据库等地方
//                flag = bookService.updateBookImage(id, fileName);
            }
            return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(Code.SAVE_ERR, "保存失败");
        }
    }

    /**
     * 模糊查询书籍信息
     * @param query
     * @return
     */
    @GetMapping("/search/{query}")
    @ResponseBody
    public Result getSearch(@PathVariable String query){
        List<Book> books = bookService.searchBook(query);
        Integer code = books != null ? Code.GET_OK : Code.GET_ERR;
        String msg = books != null ? MSG_OK : Code.MSG_ERR;
        return new Result(code, books, msg);
    }

}
